package xin.alum.aim;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import xin.alum.aim.config.AimConfig;

import java.net.InetAddress;

/**
 * Spring boot 启动后自动启动AimSocksServer
 *
 * @auther alum(alum @ live.cn)
 * @date 2021/8/2 12:38
 */
@Component
public class AimStarter implements ApplicationListener<ApplicationStartedEvent> {

    @Autowired
    NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    AimConfig aimConfig;

    @Autowired
    AimReciveService aimReciveService;

    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        regNetty();
        AIM.start();
    }


    /**
     * 注册AIM Nacos微服务
     */
    public void regNetty() {
        try {
            //获取nacos服务
            NamingService namingService = NamingFactory.createNamingService(nacosDiscoveryProperties.getNacosProperties());
            InetAddress address = InetAddress.getLocalHost();

            //将服务注册到注册中心
            namingService.registerInstance("aim-netty", address.getHostAddress(), aimConfig.getPort());
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}
